package cn.rengy.web.framework.role.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.rengy.tool.core.util._NumberUtils;
import cn.rengy.web.framework.constants.Constants;
import cn.rengy.web.framework.id.IdGenerator;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.util.GetSessionUtils;
import io.jsonwebtoken.lang.Collections;

@Service
public class RoleService {
	@Autowired
	private DbService dbService;
	private static Logger logger = LoggerFactory.getLogger(RoleService.class);
	@Autowired
	private IdGenerator idGenerator;
	/**
	 * 删除角色
	 * @param param
	 */
	public void delete(Map<String,Object> param) {
		Object ids=param.get("ids");
		this.dbService.update("update_sys_role_deleted1",Constants.YES,ids);
		//删除用户角色关系
		//String userId=GetSessionUtils.getUserId();
		this.dbService.updateBeanParameter("delete_sys_user_role",ids);
	}
	public Map<String,Object> searchAuth(Map<String,Object> param){
		Map<String,Object> result=new HashMap<String,Object>(4);
		//Long role_id=MapUtils.getLong(param, "role_id");
		Long user_id=GetSessionUtils.getUserId();
		param.put("user_id", user_id);
		//菜单授权
		List<Map<String,Object>> authMenu=this.dbService.queryForListMapParameter("select_role_auth_menu", param);
		result.put("authMenu", authMenu);
		//URI授权
		List<Map<String,Object>> authOrg=this.dbService.queryForListMapParameter("select_role_auth_resource", param);
		result.put("authURI", authOrg);
		/*//部门授权
		List<Map<String,Object>> authOrg=this.dbService.queryListBySqlId("select_role_auth_org", param);
		result.put("authOrg", authOrg);
		//资产类别授权
		List<Map<String,Object>> authAssetClass=this.dbService.queryListBySqlId("select_role_auth_assetclass", param);
		result.put("authAssetClass", authAssetClass);
		//使用地授权
		List<Map<String,Object>> authAssetPlace=this.dbService.queryListBySqlId("select_role_place", param);
		result.put("authAssetPlace", authAssetPlace);*/
		
		return result;
	}
	/**
	 * 保存角色权限信息
	 * @param paramMap
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public void saveAuth(Map<String,Object> paramMap){
		Map<String,Object> role=(Map<String,Object>)paramMap.get("role");
		Long roleId=MapUtils.getLong(role, "id");
		List<Object> menuId=(List<Object>)paramMap.get("authMenu");
		List<Object> authURI=(List<Object>)paramMap.get("authURI");
		/*
		List<Object> authAssetClass=(List<Object>)paramMap.get("authAssetClass");
		List<Object> authAssetPlace=(List<Object>)paramMap.get("authAssetPlace");*/
		if(roleId==null){//新增角色
			//保存角色信息
			roleId=idGenerator.nextId();
			role.put("id", roleId);
			this.dbService.updateMapParameter("insert_sys_role", role);
			//保存用户角色关系
			Long userId=GetSessionUtils.getUserId();
			this.dbService.update("insert_sys_user_role_rel", userId,roleId);
			//保存角色权限信息
			addAuth(roleId,1L,menuId);
			//uri访问授权
			addAuth(roleId,18415193818136576L,authURI);
			/*;
			addAuth(roleId,3L,authAssetClass);
			addAuth(roleId,4L,authAssetPlace);*/
		}else {//编辑角色
			//更新角色信息
			this.dbService.updateMapParameter("update_sys_role", role);
			//更新角色权限信息
			Map<String,Object> map1=getUpdate(1L,roleId,menuId);
			List<Object> insert1=(List<Object>)map1.get("insert");
			List<Object> delete1=(List<Object>)map1.get("delete");
			addAuth(roleId,1L,insert1);
			deleteAuth(roleId,1L,delete1);
			//uri
			Map<String,Object> map2=getUpdate(18415193818136576L,roleId,authURI);
			List<Object> insert2=(List<Object>)map2.get("insert");
			List<Object> delete2=(List<Object>)map2.get("delete");
			addAuth(roleId,18415193818136576L,insert2);
			deleteAuth(roleId,18415193818136576L,delete2);
			/*Map<String,Object> map3=getUpdate(3L,roleId,authAssetClass);
			List<Object> insert3=(List<Object>)map3.get("insert");
			List<Object> delete3=(List<Object>)map3.get("delete");
			addAuth(roleId,3L,insert3);
			deleteAuth(roleId,3L,delete3);
			Map<String,Object> map4=getUpdate(4L,roleId,authAssetPlace);
			List<Object> insert4=(List<Object>)map4.get("insert");
			List<Object> delete4=(List<Object>)map4.get("delete");
			addAuth(roleId,4L,insert4);
			deleteAuth(roleId,4L,delete4);*/
		}
		
	}
	
	private void deleteAuth(Long roleId,Long roleInfoId,List<Object> target) {
		if(!Collections.isEmpty(target)) {
			//insert into sys_role_rel(role_id,target_id,role_rel_info_id) values (?,?,?)
			List<Object[]> batchArgs=new ArrayList<Object[]>(target.size());
			for(Object obj:target) {
				Object[] param=new Object[3];
				param[0]=roleId;
				param[1]=obj;
				param[2]=roleInfoId;
				batchArgs.add(param);
			}
			this.dbService.batchUpdate("delete_sys_role_rel", batchArgs);
		}
	}
	private void addAuth(Long roleId,Long roleInfoId,List<Object> target) {
		if(!Collections.isEmpty(target)) {
			//insert into sys_role_rel(role_id,target_id,role_rel_info_id) values (?,?,?)
			List<Object[]> batchArgs=new ArrayList<Object[]>(target.size());
			for(Object obj:target) {
				Object[] param=new Object[4];
				param[0]=idGenerator.nextId();
				param[1]=roleId;
				param[2]=obj;
				param[3]=roleInfoId;
				batchArgs.add(param);
			}
			this.dbService.batchUpdate("insert_sys_role_rel", batchArgs);
		}
	}
	private Map<String,Object> getUpdate(Long roleInfoId,Long roleId,List<Object> selectedId){
		Map<String,Object> result=new HashMap<String,Object>();
		//1.查询当前角色权限信息
		List<Long> curList=this.dbService.queryForSingleColumnList("select_sys_role_rel_byroleid",Long.class, roleId,roleInfoId);
		if(selectedId!=null) {//已选择权限信息
			if(curList!=null) {
				List<Long> insert=new ArrayList<Long>();
				for(int i=0;i<selectedId.size();i++) {
					Long selectId=_NumberUtils.toLong(selectedId.get(i));
					boolean found=false;
					for(int j=0;j<curList.size();j++) {
						Long curId=curList.get(j);
						if(selectId.equals(curId)) {
							found=true;
							curList.remove(j);
							break;
						}
					}
					if(!found) {
						insert.add(selectId);
					}
				}
				result.put("insert", insert);
				//
				if(curList.size()>0) {
					result.put("delete", curList);
				}
			}else {//当前选择为空
				result.put("insert", selectedId);
			}
			
		}else {//已选择为空
			//delete from sys_role_rel where role_rel_info_id=? and role_id=?
			//删除当前选择
			result.put("delete", selectedId);
		}
		return result;
	}
}
